const $ = document.querySelector.bind(document);
const doms = {
  container: $(".upload"),
  img: $(".upload-preview"),
  select: $(".upload-select"),
  selectFiles: $(".upload-select input"),
  progress: $(".upload-progress"),

  btnCancel: $(".btn-cancel"),
  btnDel: $(".btn-del"),
};
function showArea(str) {
  doms.container.className = `upload ${str}`;
}

function setProgress(progress) {
  doms.progress.style.setProperty("--precent", progress);
}
doms.select.onclick = () => {
  doms.selectFiles.click(); //调用文件选择
};
doms.selectFiles.onchange = (e) => {
  //文件选择完成
  const file = e.target.files[0];

  const reader = new FileReader();
  reader.onload = (e) => {
    // console.log(e.target.result);
    doms.img.src = e.target.result; //生成预览
  };
  reader.readAsDataURL(file);
  setProgress(0)
  showArea("progress");
  upload(file);
};
let cancelHandler = null;

doms.btnCancel.onclick = () => {
  cancelHandler && cancelHandler();
};

doms.btnDel.onclick = () => {
  showArea("select");
  doms.img.src = "";
  setProgress(0);
};

function upload(file) {

  const xhr = new XMLHttpRequest();
  const url = "http://localhost:4060/upload";
  xhr.open("post", url, true);
  const form = new FormData();
  form.append("avatar", file);
  xhr.upload.onprogress = (ev) => {
    const num = Math.round((ev.loaded / ev.total) * 100);
    console.log("进度", num);
    setProgress(num);
  };
  xhr.onload = () => {
    console.log("上传成功");
    showArea("result");
  };
  xhr.send(form);
  cancelHandler = () => {
    xhr.abort();
    showArea("select");
    doms.img.src = "";
    cancelHandler = null;
  };
}
